<template>
    <footer class="animate__animated animate__bounceInUp animate__slow">
        <div id="myEchart" ref="chartRef"></div>
    </footer>
</template>

<script setup lang='ts' name="HomeMainFooter">
import echarts from "@/utils/echarts";
import { generateMonthGraphConfig } from './generateMonthGragh';
import { useUserStore } from "@/stores/user";
import EventEmiiter from "@/utils/EventEmiiter";
import { useMessage } from "naive-ui";
import { debounce } from "@/utils";
import { useAppStore } from '@/stores/app';
import { storeToRefs } from "pinia";
const appStore = useAppStore();
const { lang } = storeToRefs(appStore);

watch(() => lang.value, () => {
    resetChartOptions();
})


const userStore = useUserStore();
const { userInfo } = userStore;
const message = useMessage();
EventEmiiter.on('API:REQ_ERROR', (msg: string) => {
    message.error(msg);
})

const chartRef = ref<HTMLElement | null>(null)
let myChart: echarts.ECharts | null = null

// 封装 resize 函数以便卸载时移除监听
const handleResize = debounce(() => {
    myChart?.resize();
}, 500);

onMounted(() => {
    setTimeout(async () => {
        const dom = document.getElementById('myEchart');
        if (!dom) return;
        // 显示 loading 效果
        if (!chartRef.value) return
        // 初始化图表
        myChart = echarts.init(chartRef.value)
        // // 强制设置容器尺寸（确保loading时也有正确尺寸）
        // chartRef.value.style.width = '100%'
        // chartRef.value.style.height = '100%'
        resetChartOptions();
        // 添加窗口 resize 监听
        window.addEventListener('resize', handleResize);
    }, 600);
});

// 重置图标
async function resetChartOptions() {
    try {
        myChart!.showLoading({
            text: '数据加载中...',
            color: '#1890ff',
            textColor: '#000',
            maskColor: 'rgba(255, 255, 255, 0.8)',
            zlevel: 0
        });
        const options = await generateMonthGraphConfig(userInfo.id);
        myChart!.setOption(options);

        // 隐藏 loading 效果
        myChart!.hideLoading();

        // 确保 DOM 更新后执行 resize
        myChart!.resize();
    } catch (error) {
        myChart!.hideLoading();
        message.error('数据加载失败');
        console.error('图表数据加载失败:', error);
    }
};
onUnmounted(() => {
    // 移除事件监听
    window.removeEventListener('resize', handleResize);
    // 销毁图表实例
    myChart?.dispose();
});
</script>

<style scoped lang='scss'>
footer {
    grid-area: main;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.27);

    @include useTheme {
        background: getVar('rawBg');
    }

    display: flex;
    width: 100%;
    height: 100%;

    #myEchart {
        flex: 1;
    }
}
</style>